package cn.edu.ecust.market.controller;

import cn.edu.ecust.market.entity.User;
import cn.edu.ecust.market.result.Result;
import cn.edu.ecust.market.service.IUserService;
import cn.edu.ecust.market.util.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AuthController {

    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public Result<?> register(@RequestBody Map<String,String> params) {
        // 获取参数
        String username = params.get("username");
        String password = params.get("password");
        // 加密
        String hashpw = BCrypt.hashpw(password, BCrypt.gensalt());
        // 添加用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(hashpw);
        userService.save(user);
        // 返回
        return Result.success();
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String,String> params) {
        // 获取参数
        String username = params.get("username");
        String password = params.get("password");
        // 查询用户
        User user = userService.getOne(
            new LambdaQueryWrapper<User>().eq(User::getUsername, username)
        );
        // 查不到用户
        if(user == null){
            return Result.fail(401, "用户不存在");
        }
        // 认证失败
        boolean checkpw = BCrypt.checkpw(password, user.getPassword());
        if(checkpw == false){
            return Result.fail(401, "认证失败");
        }
        // 认证成功 生成jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        String token = JwtUtil.generateToken(claims, 1000L * 60 * 60 * 24 * 7);
        return Result.success(token);
    }

}
